define(function(require, exports, module){
  'use strict';
  var $ = require('jquery');
  var _const = require('seajs/fn/fnConst');
  // require('nicescroll')($);
  require('icheck')($);
  var fnUtils = require('seajs/fn/fnUtils');
  var fnData = require('seajs/fn/fnData');
  var SimpleMap = require('seajs/plugs/simpleMap');

  // EVENT start 
  function onToggleLeftMenu(){
    $('.menu-list > a').on('click', function(){
      var parent = $(this).parent();
      var sub = parent.find('> ul');
      if(sub.is(':visible')) {
        sub.slideUp(200, function(){
          parent.removeClass('nav-active');
          $('.main-content').css({height: ''});
        });
      }else{
        visibleSubMenuClose();
        parent.addClass('nav-active');
        sub.slideDown(200, function(){  
        });
      }
      return false;
    });
  }

  function onToggleLeftMenuByGid(gid){
    $('#slidebar_group_li_' + gid + ' > a').on('click', function(){
      var parent = $(this).parent();
      var sub = parent.find('> ul');
      if(sub.is(':visible')) {
        sub.slideUp(200, function(){
          parent.removeClass('nav-active');
        });
      }else{
        visibleSubMenuClose();
        parent.addClass('nav-active');
        sub.slideDown(200, function(){
        });
      }
      return false;
    });
  }

  function offToggleLeftMenu(){
    $('.menu-list > a').off('click');
  }

  function visibleSubMenuClose() {
    $('.menu-list').each(function() {
     var t = $(this);
     if(t.hasClass('nav-active')) {
        t.find('> ul').slideUp(200, function(){
          t.removeClass('nav-active');
        });
      }
    });
   }

  function icheckInit(){
    $('input[name="group_radio"]').iCheck({
      radioClass: 'iradio-group',
      increaseArea: '12%'
    });
  }

  function icheckInitByGid(gid){
    $('#group_radio_' + gid).iCheck({
      radioClass: 'iradio-group',
      increaseArea: '12%'
    });
  }

  function memeberLi(groupId, member){
    if(member){
      var memberLiHtml = [];
      memberLiHtml.push('<li id="group_' + groupId + '_member_li_' + member.memberId + '" name="member_li_' + member.memberId + '">');
      memberLiHtml.push('<a name="member_a_' + member.memberId + '" href="#">');
      if(member.status === _const.IS_ON_LINE.ON_LINE){
        if(groupId === member['inGroupId']){
          memberLiHtml.push('<img id="user_icon_group_' + groupId + '_user_icon_user_' + member.memberId + '" src="images/online.png"/>');
        }else{
          memberLiHtml.push('<img id="user_icon_group_' + groupId + '_user_icon_user_' + member.memberId + '" src="images/inother.png"/>');
        } 
      }else{
        memberLiHtml.push('<img id="user_icon_group_' + groupId + '_user_icon_user_' + member.memberId + '" src="images/offline.png"/>');
      }
      memberLiHtml.push('<span>');
      memberLiHtml.push(fnUtils.contentFormat(member.memberName, 6, 2));
      memberLiHtml.push('</span>');
      memberLiHtml.push('<i class="fa fa-commenting text-green fa-lg" style="display:none;" id="commenting_group_' + groupId + '_commenting_member_' + member.memberId + '"></i>');
      memberLiHtml.push('</a></li>');
      return memberLiHtml.join('');
    }
  }

  function groupA(group){
    if(group){
      var groupAHtml = [];
      if(group.status){
        groupAHtml.push('<a href="#" id="group_a_' + group.groupId + '">');
        groupAHtml.push('<img src="images/group.png">');
        //groupAHtml.push('<span>' + fnUtils.contentFormat(group.groupName, 5, 2) + '(<span class="group-online-num" id="group_online_num_' + group.groupId + '">'
        groupAHtml.push('<span>' + fnUtils.contentFormat(group.groupName, 6, 2) + '(<span class="group-online-num" id="group_online_num_' + group.groupId + '">'
          + group.onlineNum + '</span>/<span id="group_total_num_' + group.groupId + '">' + group.totalNum + '</span>)</span>');
        groupAHtml.push('<div class="float-right">');
        groupAHtml.push('<input type="radio" class="float-right"  id="group_radio_' + group.groupId + '" name="group_radio" value="' + group.groupId + '"');
        groupAHtml.push(' />');
        groupAHtml.push('</div>');
        groupAHtml.push('</a>');
      }else{
        groupAHtml.push('<a href="#" id="group_a_' + group.groupId + '">');
        groupAHtml.push('<img src="images/group_disable.png">');
        groupAHtml.push('<span>' + fnUtils.contentFormat(group.groupName, 5, 2) + '</span>');
        groupAHtml.push('<div class="float-right">');
        groupAHtml.push('<div class="float-right disable-group"></div>');
        groupAHtml.push('</div>');
        groupAHtml.push('</a>');
      }
      return groupAHtml.join('');
    }
  }

  // function sliderStyleInit(){
  //   $('.sidebar').niceScroll({ 
  //     cursorcolor: _const.SIDEBAR.CURSOR_COLOR,
  //     cursoropacitymax: _const.SIDEBAR.CURSOR_OPACITY_MAX,
  //     touchbehavior: _const.SIDEBAR.TOUSH_BEHAVIOR,
  //     cursorwidth: _const.SIDEBAR.CURSOR_WIDTH,
  //     cursorborder: _const.SIDEBAR.CURSOR_BORDER,
  //     cursorborderradius: _const.SIDEBAR.CURSOR_BORDER_RADIUS,
  //     autohidemode: _const.SIDEBAR.AUTO_HIDE_MODE
  //   });
  // }

  var Slidebar = function(uid, contact){
   	this.contact = contact;

    this.defaultGroup = 0;
    this.joinedGroup = 0;
    this.currendGid = undefined;

   	this.groupMap = new SimpleMap();
    this.groupIds = {disable:[], enable:[]};
   	this.memberMap = new SimpleMap();

    this.temporaryGroup = undefined;
    this.topMarker = undefined;
    this.map = undefined;
   	this.init(uid);
  }

  Slidebar.prototype.init = function(uid){
   	//sliderStyleInit();
    if(this.contact){
      $('.custom-nav').html(this.groupLi(this.contact));

   	}
    onToggleLeftMenu();
    icheckInit();
    this.memberLiClickEvent();
    if(window.localStorage){
      this.joinedGroup = parseInt(localStorage[uid + '_joined_group_id'] === undefined? 
        0: localStorage[uid + '_joined_group_id']);
    }else{
      this.joinedGroup = parseInt($.cookie(uid + '_joined_group_id')=== undefined? 
        0: $.cookie(uid + '_joined_group_id'));
    }
    if(this.joinedGroup === 0 
      || this.groupMap.get(this.joinedGroup) === undefined 
      || this.groupMap.get(this.joinedGroup).status === 0){
      this.joinedGroup = this.defaultGroup;
    }else{
      this.defaultGroup = this.joinedGroup;
    }
  };

  Slidebar.prototype.setTemporaryGroup = function(temporaryGroup){
    if(temporaryGroup){
      this.temporaryGroup = temporaryGroup;
    }
  }

  Slidebar.prototype.setJoinedGroup = function(uid, groupId){
    if(uid && groupId){
      this.joinedGroup = groupId;       
      // this.defaultGroup = this.joinedGroup;
      if(window.localStorage){
        localStorage[uid + '_joined_group_id'] = groupId;
      }else{
        $.cookie(uid + '_joined_group_id', groupId, { expires: 7 });
      }
    }
  }

  Slidebar.prototype.getJoinedGroup = function(){
    return this.joinedGroup;
  }

  Slidebar.prototype.setMap = function(map){
    if(map){
      this.map = map;
    }
  }

  Slidebar.prototype.memberUl = function(groupId, membersObj){
    if(membersObj){
      var memberUlHtml = [];
      memberUlHtml.push('<ul class="sub-menu-list" name="ul_group_' + groupId + '">');
      for(var i = 0; i < membersObj['online'].length; i++){

        var member = this.memberMap.get(membersObj['online'][i].memberId);
        if(!member){
          member = membersObj['online'][i];
          member['groups'] = new SimpleMap();
        }
        member['groups'].put(groupId,groupId);
        this.memberMap.put(member.memberId, member);
        memberUlHtml.push(memeberLi(groupId, member));
      }
      for(var j = 0; j < membersObj['inOther'].length; j++){
        var member = this.memberMap.get(membersObj['inOther'][j].memberId);
        if(!member){
          member = membersObj['inOther'][j];
          member['groups'] = new SimpleMap();
        }
        member['groups'].put(groupId,groupId);
        this.memberMap.put(member.memberId, member);
        memberUlHtml.push(memeberLi(groupId, member));
      }
      for(var k = 0; k < membersObj['offline'].length; k++){
        var member = this.memberMap.get(membersObj['offline'][k].memberId);
        if(!member){
          member = membersObj['offline'][k];
          member['groups'] = new SimpleMap();
        }
        member['groups'].put(groupId, groupId);
        this.memberMap.put(member.memberId, member);
        memberUlHtml.push(memeberLi(groupId, member));
      }
      memberUlHtml.push('</ul>');
      return memberUlHtml.join('');
    }
  }

  Slidebar.prototype.groupLi = function(groupArray){
    //这里修改slidebar列表排序
    if(groupArray){    
      var groupLiHtml = [];
      var talkGroupSelect = [];
      talkGroupSelect.push('<option value="0">全部</option>');
      this.setTotalGroupNum(groupArray.length);
      for(var i = 0; i < groupArray.length; i++){
        var group = groupArray[i];
        if(group.status){
          if(!this.defaultGroup){
            this.defaultGroup = group.groupId;
          }
          groupLiHtml.push('<li class="menu-list" id="slidebar_group_li_' + group.groupId + '">');
          this.groupMap.put(group.groupId, group);
          if(group.isSelected  == true){
            this.defaultGroup = group.groupId;
          }
          groupLiHtml.push(groupA(group));
          groupLiHtml.push(this.memberUl(group.groupId, group.members));
          groupLiHtml.push('</li>');
          talkGroupSelect.push('<option id="talk_group_option_' + group.groupId + '" value="' + group.groupId + '">' + group.groupName + '</option>');
          this.groupIds.enable.push(group.groupId);

        }else{
          this.groupMap.put(group.groupId, group);
          this.groupIds.disable.push(group.groupId);
        }
      }
      $('#talk-group-select').html(talkGroupSelect.join(''));
      for(var i = 0; i < groupArray.length; i++){
        var group = groupArray[i];
        if(!group.status){
          groupLiHtml.push('<li class="menu-list" id="slidebar_group_li_' + group.groupId + '">');
          groupLiHtml.push(groupA(group));
          groupLiHtml.push('</li>');
        }
      }

      return groupLiHtml.join('');
    }
  }
  //群组个数设置
  Slidebar.prototype.setTotalGroupNum = function(num){
    $('#totalGroupNum').html(num);
  }

  //群在线人数设置
  Slidebar.prototype.setGroupOnlineNum = function(gid, num){
    var group = this.groupMap.get(gid);
    if(group){
      group.onlineNum = group.onlineNum + num;
      $('#group_online_num_' + gid).html(group.onlineNum);
    }
  }
  //群组总人数设置
  Slidebar.prototype.setGroupTotalNum = function(gid, num){
    var group = this.groupMap.get(gid);
    if(group){
      group.totalNum = group.totalNum + num;
      $('#group_total_num_' + gid).html(group.totalNum);
    }
  }
  // Radio R
  Slidebar.prototype.checkR = function(groupId){
    $('#group_radio_' + groupId).iCheck('check');
  }

  Slidebar.prototype.enableRAll = function(){
    $('input[name="group_radio"]').iCheck('enable');
    this.groupRadioOnChanged(); 
  }

  Slidebar.prototype.disableRAll = function(){
    this.groupRadioOffChanged();
    $('input[name="group_radio"]').iCheck('disable');
  }

  Slidebar.prototype.enableR = function(groupId){
    $('#group_radio_' + groupId).iCheck('enable');
  }

  Slidebar.prototype.disableR = function(groupId){
    $('#group_radio_' + groupId).iCheck('disable');
  }

  // 语音消息提示框
  Slidebar.prototype.msgIconShow = function(groupId, memberId){
    $('i[id^="commenting_group_' + groupId + '"]').hide();
    $('#commenting_group_' + groupId + '_commenting_member_' + memberId).css('display', 'inline-block');
  }

  Slidebar.prototype.msgIconHide = function(groupId, memberId){
    $('#commenting_group_' + groupId + '_commenting_member_' + memberId).css('display', 'none');
  }

  Slidebar.prototype.memberLiClickEvent = function(){
    var self = this;
    // member click
    $('li[id*="_member_li_"]').on('click', function(){
      var memberId = $(this).attr('name').substring(10,$(this).attr('name').length);
      var groupId = $(this).parent('ul').attr('name').substring(9,$(this).parent('ul').attr('name').length);
      var member = self.memberMap.get(memberId);

      var marker = self.map.showMemberMap.get(memberId);
      var isShow = false;
      marker = self.map.markerMap.get(memberId);
      var map = self.map.map;
    
      map.panTo(member.position);
      map.setZoom(13);
      marker.setAnimation('AMAP_ANIMATION_BOUNCE');
      if(self.topMarker !== undefined){
        self.topMarker.setTop(false);
      } 
      marker.setTop(true);  
      self.topMarker = marker;
      var modal = $('#temporary_group_call');
      if(modal.attr("aria-hidden") == 'true'){
        setTimeout(function(){
          marker.setAnimation('AMAP_ANIMATION_NONE');
          self.map.drawInfoWindow(marker);
        },2500);
      }else{
        setTimeout(function(){
          marker.setAnimation('AMAP_ANIMATION_NONE');
        },2000);
      } 
    });
  }

  Slidebar.prototype.memberLiClickEventByGidAndUid = function(groupId, memberId){
    var self = this;
    //group_906_member_li_332290
    if(groupId && memberId){
      $('#group_' + groupId + '_member_li_' + memberId).on('click', function(){
        var member = self.memberMap.get(memberId);
        var marker = self.map.showMemberMap.get(memberId);
        self.checkMSM(memberId);
        if(marker === undefined){
          self.checkMSM(memberId);  
        }
        marker = self.map.markerMap.get(memberId);
        var map = self.map.map;
        map.panTo(member.position);
        map.setZoom(13);
        marker.setAnimation('AMAP_ANIMATION_BOUNCE');    
        var modal = $('#temporary_group_call');
        if(modal.attr("aria-hidden") == 'true'){
          setTimeout(function(){
            marker.setAnimation('AMAP_ANIMATION_NONE');
            self.map.drawInfoWindow(marker);
          },2500);
        }else{
          setTimeout(function(){
            marker.setAnimation('AMAP_ANIMATION_NONE');
          },2000);
        } 
      });
    }
  }

  Slidebar.prototype.memberLiClickEventByGid = function(groupId){
    var self = this;
    //group_906_member_li_332290
    if(groupId){
      $('li[id^="group_' + groupId + '_member_li_"').on('click', function(){
        var _length = (groupId+'').length;
        var memberId = $(this).attr('id').substring(_length + 17, $(this).attr('id').length);
        var member = self.memberMap.get(memberId);
        var marker = self.map.showMemberMap.get(memberId);
        marker = self.map.markerMap.get(memberId);
        var map = self.map.map;
        map.panTo(member.position);
        map.setZoom(13);
        marker.setAnimation('AMAP_ANIMATION_BOUNCE');    
        var modal = $('#temporary_group_call');
        if(modal.attr("aria-hidden") == 'true'){
          setTimeout(function(){
            marker.setAnimation('AMAP_ANIMATION_NONE');
            self.map.drawInfoWindow(marker);
          },2500);
        }else{
          setTimeout(function(){
            marker.setAnimation('AMAP_ANIMATION_NONE');
          },2000);
        } 
      });
    }
  }

  Slidebar.prototype.setTalkStatus = function(status, content){
    if(status === 1){
      $("#active-group" ).html("当前群组");
    }else{
      $("#active-group" ).html("当前状态");
    }
    $("#main_bottom_left_voice_obj").html(content);
  }
  // 切组点选按钮事件
  Slidebar.prototype.groupRadioChanged = function(radioVal, isSendWs){
    var self = this;
    var statusContent = [];
    var content = [];

    /*content.push('<span class="fa-stack fa-fw">');
    content.push('<i class="fa fa-circle fa-stack-2x text-blue"></i>');
    content.push('<i class="fa fa-users fa-stack-1x"></i>');
    content.push('</span>');*/
    if(self.groupMap.get(radioVal)){
      statusContent.push("当前群组");
      content.push(fnUtils.contentFormat(self.groupMap.get(radioVal).groupName, 6, 2));
    }else{
      statusContent.push("当前状态");
      content.push('临时对讲');
    }
    self.setTalkStatus(statusContent.join(''),content.join(''));
    $('#checkedGroupId').val(radioVal);
    if(isSendWs && self.map.ws && self.map.ws.ws.readyState == WebSocket.OPEN){
      self.map.ws.joinGroup(radioVal, _const.PTT_TYPE.TALKING);
    }
  }

  var groupRadioUncheckedByGid = function(sidebarContainer, radioVal, isSendWs){
    sidebarContainer.currendGid = undefined;
    $("#main_bottom_left_voice_obj").html('');
    $('#checkedGroupId').val(0);
    if(isSendWs && sidebarContainer.map.ws && sidebarContainer.map.ws.ws.readyState == WebSocket.OPEN){
      sidebarContainer.map.ws.exitGroup();
    }
  }

  Slidebar.prototype.groupRadioOnChanged = function(){
    var self = this;
    $('input[name="group_radio"]').on('ifChanged', function(){ 
      var radioVal = parseInt($(this).val());
      if(radioVal){
        //self.uncheckAllGMSM();
        if($(this).is(':checked')){
          self.groupRadioChanged(radioVal, true);
          self.currendGid = radioVal;
        }else{

        }
      }
    });
  }

  Slidebar.prototype.groupRadioOffChanged = function(){
    $('input[name="group_radio"]').off('ifChanged');
  }

  Slidebar.prototype.groupRadioOnChangedByGid = function(gid){
    var self = this;
    self.currendGid = gid;
    $('#group_radio_' + gid).on('ifChanged', function(){ 
      var radioVal = parseInt($(this).val());
      if(radioVal){
        //self.uncheckAllGMSM();
        if($(this).is(':checked')){
          self.groupRadioChanged(radioVal, true);
          self.currendGid = radioVal;
        }
      }
    });
  }

  Slidebar.prototype.groupRadioOffChangedByGid = function(gid){
    $('#group_radio_' + gid).off('ifChanged');
  }

  // group change
  // add
  Slidebar.prototype.addGroup = function(groupId){
    var self = this;
    fnUtils.getAddGroupInfo(self.map.ws.uid, self.map.ws.cmpid, self.map.ws.key, groupId, function(data){
      if(data.status === _const.HTTP.RES_STATUS.SUCCESS){
        var contact = [];
        contact.push(fnData.formatGroup(self.map.ws.uid, data.body, 0));
        var tmp = self.groupLi(contact);
        self.groupIds.enable = fnUtils.quickSort(self.groupIds.enable);
        self.groupIds.disable = fnUtils.quickSort(self.groupIds.disable);
        // $('.custom-nav').append();
        var group = self.groupMap.get(groupId);
        self.groupIds.enable.sort(function(a,b){return a-b});
        if(group.status){
          var pre = 0;
          for(var i in self.groupIds.enable){
            if(self.groupIds.enable[i] === groupId){
              break;
            }
            pre = self.groupIds.enable[i];
          }
          if(pre === 0){
            $('.custom-nav li:first').before(tmp);
          }else{
            $('#slidebar_group_li_' + pre).after(tmp);
          }
          onToggleLeftMenuByGid(groupId);
          icheckInitByGid(groupId);
          self.groupRadioOnChangedByGid(groupId);
          self.memberLiClickEventByGid(groupId);
        }else{
          var pre = 0;
          for(var i = self.groupIds.disable.length; i > 0; i--){
            if(self.groupIds.disable[i-1] === groupId){
              break;
            }
            pre = self.groupIds.disable[i-1];
          }
          var groupLiHtml = [];
          groupLiHtml.push('<li class="menu-list" id="slidebar_group_li_' + groupId + '">');
          groupLiHtml.push(groupA(group));
          groupLiHtml.push('</li>');
          if(pre === 0){
            $('.custom-nav').append(groupLiHtml.join(''));
          }else{
            $('#slidebar_group_li_' + pre).before(groupLiHtml.join(''));
          }
        }
        self.setTotalGroupNum(self.groupMap.size());
      }else{
        console.log('数据传输错误')
      }
    }, function(e){
      console.log(e);
    });
  }

  // member change
  // 用户上线,下线,  切组状态。
  // 切组
  Slidebar.prototype.online = function(memberId){
    var member = this.memberMap.get(memberId);
    if(member && member.groups && member['status'] === _const.IS_ON_LINE.OFF_LINE){
      for(var _gid in member.groups.map){
        var group = this.groupMap.get(_gid);
        if(group !== undefined && group['members'] !== undefined){
            var leftMemberId = 0, rightMemberId = 0, newArray = [], _newArray = [];

            for(var j in group['members']['offline']){
              if(group['members']['offline'][j].memberId !== member.memberId){
                _newArray.push(group['members']['offline'][j]);
              }
            }
            group['members']['offline'] = _newArray;

            if(group['members']['inOther'].length !== 0){
              if(member.py < group['members']['inOther'][0].py){
                newArray.push(member);
                rightMemberId = group['members']['inOther'][0].memberId;
                for(var i in group['members']['inOther']){
                  newArray.push(group['members']['inOther'][i]);
                }
                $('#group_' + _gid + '_member_li_' + memberId).insertBefore($('#group_' + _gid + '_member_li_' + rightMemberId));
                group['members']['inOther'] = newArray;
              }else if(member.py > group['members']['inOther'][group['members']['inOther'].length - 1].py){
                leftMemberId = group['members']['inOther'][group['members']['inOther'].length - 1].memberId;
                $('#group_' + _gid + '_member_li_' + memberId).insertAfter($('#group_' + _gid + '_member_li_' + leftMemberId));
                group['members']['inOther'].push(member);
              }else{
                newArray.push(group['members']['inOther'][0]);
                for(var i = 1; i < group['members']['inOther'].length; i++){
                  if(group['members']['inOther'][i].py > member.py && rightMemberId === 0){
                    newArray.push(member);
                    rightMemberId = group['members']['inOther'][i].memberId;
                  }
                  newArray.push(group['members']['inOther'][i]);
                }
                $('#group_' + _gid + '_member_li_' + memberId).insertBefore($('#group_' + _gid + '_member_li_' + rightMemberId));
                group['members']['inOther'] = newArray;
              }
            }else{
              group['members']['inOther'].push(member);
              if(group['members']['online'].length > 0){
                leftMemberId = group['members']['online'][group['members']['online'].length -1].memberId;
                $('#group_' + _gid + '_member_li_' + memberId).insertAfter($('#group_' + _gid + '_member_li_' + leftMemberId));
              }else{
                $('#group_' + _gid + '_member_li_' + memberId).insertBefore($('ul[name="ul_group_' + _gid + '"] li:first-child'));
              }
            }

            //前端渲染
            this.setGroupOnlineNum(_gid, 1);
            $('#user_icon_group_' + _gid + '_user_icon_user_' + memberId).attr("src","images/inother.png");
        }     
      }
      this.memberMap.get(memberId)['status'] = _const.IS_ON_LINE.ON_LINE;
    }
  }

  Slidebar.prototype.offline = function(memberId){
    var member = this.memberMap.get(memberId);
    if(member && member.groups && member['status'] && member['status'] !== _const.IS_ON_LINE.OFF_LINE){
      this.memberMap.get(memberId)['status'] = _const.IS_ON_LINE.OFF_LINE;
      for(var _gid in member.groups.map){
        var group = this.groupMap.get(_gid);
        if(group !== undefined && group['members'] !== undefined){
          var leftMemberId = 0, rightMemberId = 0, newArray = [], _newArray = [];
          if(member['inGroupId'] == _gid){
            for(var i in group['members']['online']){
              if(group['members']['online'][i].memberId !== member.memberId){
                newArray.push(group['members']['online'][i]);
              }
            }
            group['members']['online'] = newArray;
          }else{
            for(var i in group['members']['inOther']){
              if(group['members']['inOther'][i].memberId !== member.memberId){
                newArray.push(group['members']['inOther'][i]);
              }
            }
            group['members']['inOther'] = newArray;
          }

          if(group['members']['offline'].length > 0){
            if(member.py < group['members']['offline'][0].py){
              _newArray.push(member);
              rightMemberId = group['members']['offline'][0].memberId;
              for(var j in group['members']['offline']){
                _newArray.push(group['members']['offline'][j]);
              }
              group['members']['offline'] = _newArray;
              $('#group_' + _gid + '_member_li_' + memberId).insertBefore($('#group_' + _gid + '_member_li_' + rightMemberId));
            }else if(member.py > group['members']['offline'][group['members']['offline'].length - 1].py){
              group['members']['offline'].push(member);
              $('#group_' + _gid + '_member_li_' + memberId).insertAfter($('ul[name="ul_group_' + _gid + '"] li:last-child'));
            }else{
              _newArray.push(group['members']['offline'][0]);
              for(var j = 1; j < group['members']['offline'].length; j++){
                if(group['members']['offline'][j].py > member.py && leftMemberId === 0){
                  _newArray.push(member);
                  leftMemberId = group['members']['offline'][j-1].memberId;
                }
                _newArray.push(group['members']['offline'][j]);
              }
              group['members']['offline'] = _newArray;
              $('#group_' + _gid + '_member_li_' + memberId).insertAfter($('#group_' + _gid + '_member_li_' + leftMemberId));
            }
          }else{
            group['members']['offline'].push(member);
            $('#group_' + _gid + '_member_li_' + memberId).insertAfter($('ul[name="ul_group_' + _gid + '"] li:last-child'));
          }
          this.setGroupOnlineNum(_gid, -1);
          $('#user_icon_group_' + _gid + '_user_icon_user_' + memberId).attr("src","images/offline.png");
        }
      }
      this.memberMap.get(memberId)['inGroupId'] = 0;
    }
  }

  Slidebar.prototype.memberEnable = function(memberId){
    // nothing do
  }
  Slidebar.prototype.memberDisable = function(memberId){
    this.offline(memberId);
  }
  Slidebar.prototype.positionTime=undefined;
  Slidebar.prototype.latLng=undefined;
  Slidebar.prototype.clickUid=[];
  Slidebar.prototype.cutSet = function(gid, memberId, msg){
    var self=container;
    var member = this.memberMap.get(memberId);
    var groupName;
    Slidebar.prototype.cutUid=memberId;
    for(var i=0;i<this.contact.length;i++){
      if(gid==this.contact[i].groupId){
        groupName=this.contact[i].groupName;
        break;
      }
    }
    if(!groupName){groupName='无'}
    //Slidebar.prototype.cutGroupName=groupName;
    if(member !== undefined && member.groups 
      && member['status'] === _const.IS_ON_LINE.ON_LINE 
      && gid !== member['inGroupId']){
      var _group = this.groupMap.get(member['inGroupId']);
      if(_group !== undefined && _group['members'] !== undefined){
        var leftMemberId = 0, rightMemberId = 0, newArray = [], _newArray = [];
        for(var i in _group['members']['online']){
          if(_group['members']['online'][i].memberId !== memberId){
            newArray.push(_group['members']['online'][i]);
          }
        }
        _group['members']['online'] = newArray;
        if(_group['members']['inOther'].length !== 0){
          if(member.py < _group['members']['inOther'][0].py){
            _newArray.push(member);
            rightMemberId = _group['members']['inOther'][0].memberId;
            for(var j in _group['members']['inOther']){
              _newArray.push(_group['members']['inOther'][j]);
            }
            _group['members']['inOther'] = _newArray;
            $('#group_' + member['inGroupId'] + '_member_li_' + memberId).insertBefore($('#group_' + member['inGroupId'] + '_member_li_' + rightMemberId));
          }else if(member.py > _group['members']['inOther'][_group['members']['inOther'].length - 1].py){
            leftMemberId = _group['members']['inOther'][_group['members']['inOther'].length - 1].memberId;
            _group['members']['inOther'].push(member);
            $('#group_' + member['inGroupId'] + '_member_li_' + memberId).insertAfter($('#group_' + member['inGroupId'] + '_member_li_' + leftMemberId));
          }else{
            _newArray.push(_group['members']['inOther'][0]);
            for(var j = 1; j < _group['members']['inOther'].length; j++){
              if(_group['members']['inOther'][j].py > member.py && leftMemberId === 0){
                _newArray.push(member);
                leftMemberId = _group['members']['inOther'][j-1].memberId;
              }
              _newArray.push(_group['members']['inOther'][j]);
            }
            _group['members']['inOther'] = _newArray;
            $('#group_' + member['inGroupId'] + '_member_li_' + memberId).insertAfter($('#group_' + member['inGroupId'] + '_member_li_' + leftMemberId));
          }
        }else{
          _group['members']['inOther'].push(member);
          if(_group['members']['online'].length > 0){
            leftMemberId = _group['members']['online'][_group['members']['online'].length -1].memberId;
            $('#group_' + member['inGroupId'] + '_member_li_' + memberId).insertAfter($('#group_' + member['inGroupId'] + '_member_li_' + leftMemberId));
          }else{
            $('#group_' + member['inGroupId'] + '_member_li_' + memberId).insertBefore($('ul[name="ul_group_' + member['inGroupId'] + '"] li:first-child'));
          }
        }
        $('#user_icon_group_' + member['inGroupId'] + '_user_icon_user_' + memberId).attr("src","images/inother.png");
      }
      
      // 切当前组
      var _curGroup = this.groupMap.get(gid);
      if(_curGroup !== undefined && _curGroup['members'] !== undefined){
        var leftMemberId = 0, rightMemberId = 0, newArray = [], _newArray = [];
        for(var j in _curGroup['members']['inOther']){
          if(_curGroup['members']['inOther'][j].memberId !== memberId){
            _newArray.push(_curGroup['members']['inOther'][j]);
          }
        }
        _curGroup['members']['inOther'] = _newArray;
        if(_curGroup['members']['online'].length !== 0){
          if(member.py < _curGroup['members']['online'][0].py){
            newArray.push(member);
            for(var i in _curGroup['members']['online']){
              newArray.push(_curGroup['members']['online'][i]);
            }
            _curGroup['members']['online'] = newArray;
            $('#group_' + gid + '_member_li_' + memberId).insertBefore($('ul[name="ul_group_' + gid + '"] li:first-child'));
          }else if(member.py > _curGroup['members']['online'][_curGroup['members']['online'].length - 1].py){
            leftMemberId = _curGroup['members']['online'][_curGroup['members']['online'].length - 1].memberId;
            $('#group_' + gid + '_member_li_' + memberId).insertAfter($('#group_' + gid + '_member_li_' + leftMemberId));
             _curGroup['members']['online'].push(member);
          }else{
            newArray.push(_curGroup['members']['online'][0]);
            for(var i = 1; i < _curGroup['members']['online'].length; i++){
              if(_curGroup['members']['online'][i].py > member.py && leftMemberId === 0){
                leftMemberId = _curGroup['members']['online'][i-1].memberId;
                newArray.push(member);
              }
              newArray.push(_curGroup['members']['online'][i]);
            }
            _curGroup['members']['online'] = newArray;
            $('#group_' + gid + '_member_li_' + memberId).insertAfter($('#group_' + gid + '_member_li_' + leftMemberId));
          }
        }else{
           _curGroup['members']['online'].push(member);
          $('#group_' + gid + '_member_li_' + memberId).insertBefore($('ul[name="ul_group_' + gid + '"] li:first-child'));
        }
        $('#user_icon_group_' + gid + '_user_icon_user_' + memberId).attr("src","images/online.png");
      }
      member['inGroupId'] = gid;       
    }
  }

  // add Member
  Slidebar.prototype.addMember = function(groupId, uid){
    var self = this;
    var member = self.memberMap.get(uid);
    var memberLi = document.getElementById('group_' + groupId + '_member_li_' + uid);
    if(!memberLi){
      if(!member){
        fnUtils.getAddMemberInfo(self.map.ws.uid, self.map.ws.cmpid, self.map.ws.key, uid, function(data){
           self._addMember(groupId, fnData.formatMember(data, groupId));
        }, function(e){
          console.log(e);
        });
      }else{
        self._addMember(groupId, member);
      }
    }
  }

  Slidebar.prototype._addMember = function(groupId, member){
    var group = this.groupMap.get(groupId);
    if(group && member){
      if(!member['groups']){
        member['groups'] = new SimpleMap();
      }
      member['groups'].put(groupId, groupId);
      this.setGroupTotalNum(groupId, 1);
      if(member.status === _const.IS_ON_LINE.OFF_LINE){
        var leftMemberId = 0, rightMemberId = 0,  newArray = [];
        if(group['members']['offline'].length === 0){
          newArray.push(member);
        }else{
          for(var i in group['members']['offline']){
            if(group['members']['offline'][i].py > member.py && rightMemberId == 0){
              newArray.push(member);
              if(i > 0){
                leftMemberId = group['members']['offline'][i - 1].memberId;
              }
              rightMemberId = group['members']['offline'][i].memberId;
            }
            newArray.push(group['members']['offline'][i]);
          }
          if(newArray.length === group['members']['offline'].length){
            newArray.push(member);
            leftMemberId = group['members']['offline'][group['members']['offline'].length - 1].memberId;
          }
        }
        group['members']['offline'] = newArray;
        if(group.status){
          if(leftMemberId > 0){
            $('#group_' + groupId + '_member_li_' + leftMemberId).after(memeberLi(groupId, member));
          }else if(rightMemberId > 0){
            $('#group_' + groupId + '_member_li_' + rightMemberId).before(memeberLi(groupId, member));
          }else{
            $('ul[name="ul_group_' + groupId + '"]').append(memeberLi(groupId, member));
          }
        }
      }else{
        this.setGroupOnlineNum(groupId, 1);
        if(member['inGroupId'] !== groupId){
          var onlineFirstMemberId = 0, leftMemberId = 0, rightMemberId = 0, newArray = [];
          if(group['members']['inOther'].length === 0){
            newArray.push(member);
          }else{
            for(var i in group['members']['inOther']){
              if(group['members']['inOther'][i].py > member.py && rightMemberId === 0){
                if(i > 0){
                  leftMemberId = group['members']['inOther'][i - 1].memberId;
                }
                rightMemberId = group['members']['inOther'][i].memberId
                newArray.push(member);
              }
              newArray.push(group['members']['inOther'][i]);
            }

          }
          if(newArray.length === group['members']['inOther'].length){
            leftMemberId = group['members']['inOther'][group['members']['inOther'].length - 1].memberId;
            newArray.push(member);
          }
          group['members']['inOther'] = newArray;

          if(group['members']['online'].length > 0){
            onlineFirstMemberId = group['members']['online'][group['members']['online'].length - 1].memberId;
          }
          if(group.status){
            if(leftMemberId > 0){
              $('#group_' + groupId + '_member_li_' + leftMemberId).after(memeberLi(groupId, member));
            }else if(rightMemberId > 0){
              $('#group_' + groupId + '_member_li_' + rightMemberId).before(memeberLi(groupId, member)); 
            }else if(onlineFirstMemberId > 0){
              $('#group_' + groupId + '_member_li_' + onlineFirstMemberId).after(memeberLi(groupId, member));
            }else{
              $('ul[name="ul_group_' + groupId + '"] li:first').before(memeberLi(groupId, member));
            }
          }
        }
      }
      this.memberLiClickEventByGidAndUid(groupId, member.memberId);
      this.memberMap.put(member.memberId, member);
    }
  }

  // remove
  Slidebar.prototype.removeMember = function(groupId, memberId){
    //group_' + groupId + '_member_li_' + member.memberId
    var group = this.groupMap.get(groupId);
    var member = this.memberMap.get(memberId);
    if(group){
      if(member){
        if(member.status !== _const.IS_ON_LINE.OFF_LINE){
          this.setGroupOnlineNum(groupId, -1);
        }
      }
      this.setGroupTotalNum(groupId, -1);
      var newArray = [];
      member['groups'].remove(groupId);
      if(member.status === _const.IS_ON_LINE.ON_LINE){
        if(groupId === member['inGroupId']){
          for(var i in group['members']['online']){
            if(group['members']['online'][i].memberId !== memberId){
              newArray.push(group['members']['online'][i]);
            }
          }
          group['members']['online'] = newArray;
        }else{
          for(var i in group['members']['inOther']){
            if(group['members']['inOther'][i].memberId !== memberId){
              newArray.push(group['members']['inOther'][i]);
            }
          }
          group['members']['inOther'] = newArray;
        }
      }else{
        for(var i in group['members']['offline']){
          if(group['members']['offline'][i].memberId !== memberId){
            newArray.push(group['members']['offline'][i]);
          }
        }
        group['members']['offline'] = newArray;
      }
      
      $('#group_' + groupId + '_member_li_' + memberId).remove();
    }else{
      if(member){
        for(var i in member['groups'].map){
          var _group = this.groupMap.get(i);
          var newArray = [];
          if(member.status === _const.IS_ON_LINE.OFF_LINE){
            if(member['inGroupId'] === i){
              for(var j = 0; j < _group['members']['online'].length; j++ ){
                if(_group['members']['online'][j].memberId !== memberId){
                  newArray.push(_group['members']['online'][j]);
                }
              }
            }else{
              for(var j = 0; j < _group['members']['inOther'].length; j++ ){
                if(_group['members']['inOther'][j].memberId !== memberId){
                  newArray.push(_group['members']['inOther'][j]);
                }
              }
            }
          }else{
            for(var j = 0; j < _group['members']['offline'].length; j++ ){
              if(_group['members']['offline'][j].memberId !== memberId){
                newArray.push(_group['members']['offline'][j]);
              }
            }
          }
          _group['members'] = newArray;
        }
      }
      this.memberMap.remove(memberId);
      $('li[id$="_member_li_' + memberId + '"]').remove();
    }
  }

  Slidebar.prototype.deleteMember = function(memberId){
    var member = this.memberMap.get(memberId);
    for(var _gid in member.groups.map){
      this.removeMember(_gid, memberId);
    }
  }

  Slidebar.prototype.groupDisable = function(gid){
    var group = this.groupMap.get(gid);

    if(group !== undefined){
      group.status = 0;
      var groups = [];
      for(var i in this.groupMap.map){
        if(this.groupMap.get(i)['status'] === 1){
          groups.push(this.groupMap.get(i));
        }
      }
      if(groups.length > 0){
        if(!this.defaultGroup 
          || this.defaultGroup === gid 
          || this.groupMap.get(this.defaultGroup) !== undefined){
          this.defaultGroup = groups[0].groupId;
        }
        if(this.map.ws.tasks.currentId === undefined){
          this.checkR(this.defaultGroup);
        }else{
          // 加入新组， 不加入对讲
          this.groupRadioOffChangedByGid(this.defaultGroup);
          this.checkR(this.defaultGroup);
          this.groupRadioOnChangedByGid(this.defaultGroup);
        }
      }else{
        this.defaultGroup = undefined;
        if(this.map.ws.tasks.currentId === undefined){
          this.map.ws.exitGroup();
        }
      }
      var newArray = [], _newArray = [], rightGroupId = 0;
      if(this.groupIds.disable.length === 0){
        newArray.push(gid);
      }else{
        for(var i in this.groupIds.disable){
          if(gid < this.groupIds.disable[i] && rightGroupId === 0){
            newArray.push(gid);
            rightGroupId = this.groupIds.disable[i];
          }
          newArray.push(this.groupIds.disable[i]);
        }
      }
      this.groupIds.disable = newArray;

      for(var j in this.groupIds.enable){
        if(gid != this.groupIds.enable[j]){
          _newArray.push(this.groupIds.enable[j]);
        }
      }
      this.groupIds.enable = _newArray;

      $('#slidebar_group_li_' + gid).remove();
      var groupLiHtml = [];
      groupLiHtml.push('<li class="menu-list" id="slidebar_group_li_' + gid + '">');
      groupLiHtml.push(groupA(group));
      groupLiHtml.push('</li>');
      if(rightGroupId > 0){
        $('#slidebar_group_li_' + rightGroupId).before(groupLiHtml.join(''));
      }else{
        $('.custom-nav').append(groupLiHtml.join(''));
      }
    }
  }

  Slidebar.prototype.groupEnable = function(gid){
    var group = this.groupMap.get(gid);
    group.status = 1;
    if(group){
      var newArray = [], _newArray = [], leftGroupId = 0;
      if(this.groupIds.enable.length === 0){
        newArray.push(gid);
      }else{
        for(var i in this.groupIds.enable){
          if(gid < this.groupIds.enable[i] && leftGroupId === 0){
            newArray.push(gid);
            if(i === 0){
              leftGroupId = -1;
            }else{
              leftGroupId = this.groupIds.enable[i - 1];
            }
          }
          newArray.push(this.groupIds.enable[i]);
        }
        if(newArray.length === this.groupIds.enable.length){
          leftGroupId = this.groupIds.enable[this.groupIds.enable.length - 1];
          newArray.push(gid);
        }
      }
      this.groupIds.enable = newArray;

      for(var j in this.groupIds.disable){
        if(gid != this.groupIds.disable[j]){
          _newArray.push(this.groupIds.disable[j]);
        }
      }
      this.groupIds.disable = _newArray;
      $('#slidebar_group_li_' + gid).remove();

      var groupLiHtml = [];
      groupLiHtml.push('<li class="menu-list" id="slidebar_group_li_' + gid + '">');
      groupLiHtml.push(groupA(group));
      groupLiHtml.push(this.memberUl(group.groupId, group.members));
      groupLiHtml.push('</li>');
      if(leftGroupId > 0){
        $('#slidebar_group_li_' + leftGroupId).after(groupLiHtml.join(''));
      }else{
        $('.custom-nav li:first').before(groupLiHtml.join(''));
      }
      onToggleLeftMenuByGid(gid);
      icheckInitByGid(gid);
      this.groupRadioOnChangedByGid(gid);
      this.memberLiClickEventByGid(gid);
    }

  }

  Slidebar.prototype.groupDelete = function(gid){
    var group = this.groupMap.get(gid);
    if(group !== undefined){
      this.groupMap.remove(gid);
      var groups = this.groupMap.values();
      if(groups.length > 0){
        if(!this.defaultGroup 
          || this.defaultGroup === gid 
          || this.groupMap.get(this.defaultGroup) !== undefined){
          this.defaultGroup = groups[0].groupId;
        }
        if(this.map.ws.tasks.currentId === undefined){
          this.checkR(this.defaultGroup);
        }else{
          // 加入新组， 不加入对讲
          this.groupRadioOffChangedByGid(this.defaultGroup);
          this.checkR(this.defaultGroup);
          this.groupRadioOnChangedByGid(this.defaultGroup);
        }
      }else{
        this.defaultGroup = undefined;
        if(this.map.ws.tasks.currentId === undefined){
          this.map.ws.exitGroup();
        }
      }
      //ui
      var newArray = [], _newArray = [];
      for(var i in this.groupIds.enable){
        if(gid != this.groupIds.enable[i]){
          newArray.push(this.groupIds.enable[i]);
        }
      }
      this.groupIds.enable = newArray; 

      for(var j in this.groupIds.disable){
        if(gid != this.groupIds.disable[j]){
          _newArray.push(this.groupIds.disable[j]);
        }
      }
      this.groupIds.disable = _newArray;
      $('#slidebar_group_li_' + gid).remove();
      // 下拉多选
      var _gid = $('#talk-group-select option:selected').val();
    }
    
    this.setTotalGroupNum(this.groupMap.size());
  }

  return Slidebar;

});